//
//  PageHContr.m
//  丁诚昊的外包项目(2016_V7宝)
//
//  Created by DimChum_Haul on 16/3/25.
//  Copyright © 2016年 沙罗双树831. All rights reserved.
//
#import "PageHContr.h"
#import "Masonry.h" ///布局方式
#import "Pay4GDBlock.h"

#import "UIColor+ColorFullTemplate.h" ///分类
#import "UIView+Geometry.h"
#import "UIView+PhyMoVal.h"
#import "PINImageView+PINRemoteImage.h"
#import "FlowCube.h" //FlowLayout
#import "FlowListObj.h"

#import "ObjCBlock_Am_SwiftClosure.h" /// block工具
#import "AFNetworking.h"
#import "PostsAFN.h"
#import "SVProgressHUD.h" 
#define TimeDuration 3.0f

@interface PageHContr ()<UIScrollViewDelegate>

@property (nonatomic,strong,readwrite,getter=viewSrl) UIScrollView* contentView;

@property (strong,nonatomic)NSMutableArray<FlowListObj*>* FlowPool;

/**  
 *            -------------  瀑布流控件 -------------
 * 最后达到的效果 直接传入一个bo数就能获取服务器上对应的(PerNumber*BoNumber)条数据
 */
@property (strong,nonatomic,readwrite) FlowCube* FlowCube;

/// 全局UI记忆指针
@property (assign) CGFloat ptr2UILoaction;

/// 是否准备刷新
@property(nonatomic, assign) BOOL isAllowedRequest;
@property (strong,nonatomic)UIView* ptrVoid;
@end

@implementation PageHContr
#pragma mark - LifeCycle & Override

static NSUInteger timeCount = 0;
- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"浏览商品";
    self.view.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:self.viewSrl];
    [self.viewSrl makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    /// 2.计算瀑布流高度和UI渲染 拿到最终的高度 刷新指针的值
    CGFloat finalBottom = [self makeUpFlowCubeByBoNumber:14];
    
    // 1.更改🔋状态栏
    [UIView statusBatteryHSBView:self.navigationController.view
                         WithTag:-1];
    
    /// 3.丁诚昊阴影
    [self makeShaowCanvas:kscreenW / arc4randomByRange(1,2) withHeight:finalBottom];
    
    Pay4GDBlock* TT = [[Pay4GDBlock alloc]init];
    [self.viewSrl addSubview:TT];
    [TT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.equalTo(self.viewSrl);
        make.size.equalTo(CGSizeMake(kscreenW, 49));
    }];
    self.ptrVoid = TT;
    
    [self setUpTimer];
}

- (void) setUpTimer{
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(running) userInfo:@{@"countingNum":@(timeCount)} repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    [timer fire];
}

- (void)running{
    timeCount++;
    
//    [self.ptrVoid mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(64).offset(timeCount>=10?(timeCount/2)*5:timeCount*5);
//    }];
//    [self.view setNeedsUpdateConstraints];
//    [self.view updateConstraintsIfNeeded];
//    [UIView animateWithDuration:timeCount/10 animations:^{
//        [self.view layoutIfNeeded];
//    }];
}

-(void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    // 2.调试网络数据
    if ([self isViewLoaded]){
        if(self.isAllowedRequest){
            [self request4HTTByAFN_withPageParameter:1];
        }
    }
}

-(BOOL) isAllowedRequest{
    return timeCount <= 10;
}

#pragma mark - Getter & Setter
- (UIScrollView *)viewSrl
{
    if (!_contentView)
    {
        UIScrollView *contentView = [UIScrollView new];
        contentView.frame = self.view.bounds;
        contentView.showsVerticalScrollIndicator   = YES;
        contentView.showsHorizontalScrollIndicator = NO;
        contentView.contentSize = CGSizeZero;
        contentView.delegate = self;
        self.contentView = contentView;
    }
    return _contentView;
}

- (NSMutableArray<FlowListObj *> *)FlowPool{
    //1.首先从缓存中读取 然后等待主页底层指令集是否需要刷新 如果网络通达则刷新 否则默认加载IO缓存数据
    if (!_FlowPool) {
        self.FlowPool = [NSMutableArray arrayWithCapacity:10];
    }
    return _FlowPool;
}

#pragma mark - Netting
- (void)setUpConfigurationAboutSVG {
    SVProgressHUD* shareOne = [SVProgressHUD sharedView];
    [shareOne setDefaultStyle:SVProgressHUDStyleCustom];
    [shareOne setBackgroundColor:[UIColor purpleColor]];
    [shareOne setForegroundColor:[UIColor grayGrayColor]];
    [shareOne setFadeInAnimationDuration:1.5f];
    [shareOne setRingThickness:10.0f];
    [SVProgressHUD showWithStatus:@"更新"];
}

/**
 * 拟态： 按钮的tag值就代表请求API的分页参数 同时渲染到UI
 */
-(void) request4HTTByAFN_withPageParameter:(NSUInteger)pagerNumber {
    
    [self setUpConfigurationAboutSVG];
    
    [[AFHTTPSessionManager manager] POST:@"https://www.baidu.com" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:responseObject
                                                             options:NSJSONReadingAllowFragments
                                                               error:nil];
        NSString* chinese = [PostsAFN ChineseFromJSONDict:dict];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"请求失败"];
            NSLog(@"打印中文结果集-—->%@",chinese);
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(TimeDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"请求失败结果集-—->%@",error);
            [SVProgressHUD showImage:[UIImage imageNamed:@"lock"] status:@"Success"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(TimeDuration/3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD popActivity];
            });
        });
    }];
}

- (CGFloat)makeUpFlowCubeByBoNumber:(NSUInteger)BoNum{
    if (!_FlowCube) {
        self.FlowCube = [[FlowCube alloc]initWithBoNumber:BoNum];
        self.FlowCube.collectionView.scrollEnabled = NO;
        self.FlowCube.collectionView.showsVerticalScrollIndicator = NO;
    }
    [self.viewSrl addSubview:self.FlowCube.collectionView];
    
    ///计算瀑布流占据的最终高度
    CGFloat finalHeightOfCoView = [self.FlowCube finalHeightOfFlow];
    
    [self.FlowCube.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.viewSrl).offset(kscreenH/2);
        self.ptr2UILoaction = kscreenH/2;
        make.height.equalTo(finalHeightOfCoView);
    }];
    
    [self.viewSrl mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.FlowCube.collectionView.mas_bottom).offset(44);
    }];
    
    /// 返回瀑布流占据的最终高度
    return finalHeightOfCoView;
}

#pragma mark - Private Methods
/** 
 @callee [self makeShaowCanvas:kscreenW / (arc4random_uniform(10)+1)];
 丁诚昊阴影
 */
-(void) makeShaowCanvas:(NSUInteger)numberOfCanvas withHeight:(CGFloat)height
{
    CGFloat perW = kscreenW / numberOfCanvas;
    
    UIView* ptr2LastCanvas = nil; ///记忆指针
    CGFloat alphaPerPixel = 1.0 / (numberOfCanvas / 2) ;
    
    CGFloat deviceScale = kscreenW / (height + self.ptr2UILoaction);
    UIColor *color = [UIColor grayGrayColor];
    for (int i = 0 ; i < numberOfCanvas;i++)
    {
        UIView* randomView = [UIView new];
        randomView.backgroundColor = color;
        
        if( i < numberOfCanvas / 2) {
            randomView.alpha = alphaPerPixel * i;
        }else{
            randomView.alpha =  1 - (i - numberOfCanvas / 2) * alphaPerPixel ;
        }
        [self.viewSrl addSubview:randomView];
        
        [randomView mas_makeConstraints:^(MASConstraintMaker *make) {
            if (ptr2LastCanvas == nil){
                make.left.equalTo(self.viewSrl.mas_left);
            }
            else{
                make.left.equalTo(ptr2LastCanvas.mas_right);
            }
            make.top.equalTo(self.viewSrl);
            make.width.equalTo(perW);
            make.bottom.equalTo(randomView.mas_right).dividedBy(deviceScale);
        }];
        ptr2LastCanvas = randomView;
    }
}

@end
